import os
import sys
import re

from configmod import misc
from configmod import generic
import paths as routerconf

def hostname(hostname):
    """Change hostname modifying /etc/hostname and /etc/hosts.""" 
    modified_files = []
    commands = []
    
    # /etc/hostname
    hostname_filename = routerconf.filenames["hostname"]
    modified = generic.overwrite_file(hostname_filename, [hostname])
    if modified:
        commands.append(["hostname", hostname])
        modified_files.append(hostname_filename)
    
    # /etc/hosts
    hosts_filename = routerconf.filenames["hosts"]
    lines = generic.readlines(hosts_filename)
    variables = [("127.0.0.1", "localhost %s" % hostname)]
    new_lines = generic.update_variables_plain(lines, variables,
       assignation="^([0-9.]+)\s+(.*?)\s*$", output_format='%s %s')    
    if generic.overwrite_file(hosts_filename, new_lines):
        modified_files.append(hosts_filename)
    return modified_files, commands

def hostname_get(general):
    lines = filter(bool, map(str.strip, 
        open(routerconf.filenames["hostname"]).readlines()))
    if not lines:
        return
    general["hostname"] = lines[0] 
    
def ntpdate(servers, unprevileged=True):
    """Change ntpdate configuration (/etc/default/ntpdate).""" 
    modified_files = []
    ntpdate_filename = routerconf.filenames["ntpdate"]
    lines = generic.readlines(ntpdate_filename)
    options = []
    if unprevileged:
        options.append("-u")
    variables = [
        ("NTPSERVERS", " ".join(servers)),
        ("NTPOPTIONS", " ".join(options)),
    ]
    new_lines = generic.update_variables_plain(lines, variables, 
        assignation='\s*([^=]+)="?(.*?)"?\s*$', output_format='%s="%s"')
    if generic.overwrite_file(ntpdate_filename, new_lines):
        modified_files.append(ntpdate_filename)
    return modified_files, []

def ntpdate_get(general):
    contents = open(routerconf.filenames["ntpdate"]).read()
    match = re.search("^\s*NTPSERVERS=(.*)$", contents, re.MULTILINE)
    if not match:
        value = []
    else:
        value = match.group(1).strip().strip("'\"").strip().split()
    general["ntp_servers"] = value 
         
def dns(servers):
    """Change DNS configuration on /etc/hosts."""
    modified_files = []
    
    resolvfile = routerconf.filenames["resolvconf"]
    output = []
    for line in open(resolvfile):
        match = re.match("nameserver\s+([0-9.]+)$", line.strip())
        if not match:
            output.append(line)
        elif match.group(1) not in servers:
            output.append("# "+line)
    output.extend("nameserver %s" % server for server in servers if server)            
    if generic.overwrite_file(resolvfile, output):
        modified_files.append(resolvfile)
    return modified_files, []

def dns_get(general):
    contents = open(routerconf.filenames["resolvconf"]).read()
    values = re.findall("^\s*nameserver\s+(.*)$", contents, re.MULTILINE)
    if len(values) == 0:
        dns1 = dns2 = None
    elif len(values) == 1:
        dns1 = values[0]
        dns2 = None
    else:
        dns1, dns2 = values[:2]
    if dns1:
        general["dns_primary"] = dns1
    elif "dns_primary" in general:
        del general["dns_primary"]
    if dns2:
        general["dns_secondary"] = dns2
    elif "dns_secondary" in general:
        del general["dns_secondary"] 
